package com.lufan.controller;

import com.google.gson.Gson;
import com.lufan.data.dto.DownloadInfo;
import com.lufan.data.dto.VideoDownLoadDto;
import com.lufan.data.entity.VideoBasicInfoEntity;
import com.lufan.enums.ApiEnum;
import com.lufan.factory.HttpClientFactory;
import com.lufan.service.VideoDownloadService;
import com.lufan.util.DownloadUtil;
import com.lufan.util.HttpUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/video")

public class VideoController {
    private static final Gson gson = new Gson();
    private static final OkHttpClient client = HttpClientFactory.getHttpClient();
    @Autowired
    private VideoDownloadService videoDownloadService;
    @Value("${download.path}")
    private String downloadPath;
    private static final Logger log = LoggerFactory.getLogger(VideoController.class);


    @GetMapping("/info")
    public VideoBasicInfoEntity getVideoBasicInfo(@RequestParam String videoUrl) {
        String bvid = DownloadUtil.parseBvid(videoUrl);
        if (bvid == null) {
            throw new RuntimeException("无效的视频URL");
        }
        String url = ApiEnum.VIDEO_BASIC_INFO.getUrl() + "?bvid=" + bvid;
        Response response = null;
        VideoBasicInfoEntity basicInfo = null;
        try {
            response = HttpUtil.sendGet(client, url);
            if (!response.isSuccessful()) {
                throw new RuntimeException("获取视频信息失败: " + response.code());
            }
            String data = response.body().string();
            basicInfo = gson.fromJson(data, VideoBasicInfoEntity.class);
            if (basicInfo == null || basicInfo.getData() == null) {
                throw new RuntimeException("解析视频信息失败");
            }
            return basicInfo;
        } catch (IOException e) {
            throw new RuntimeException("获取视频信息异常: " + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    @GetMapping("/image")
    public ResponseEntity<byte[]> proxyImage(@RequestParam String url) {
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Referer", "https://www.bilibili.com/")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                byte[] imageBytes = response.body().bytes();
                String contentType = response.header("Content-Type", "image/jpeg");
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType(contentType));
                headers.setCacheControl("max-age=3600");
                response.close();
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(imageBytes);
            } else {
                response.close();
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).build();
        }
    }

    @PostMapping("/download")
    public void download(@RequestBody VideoDownLoadDto request) {
        if (request == null || request.getVideoList() == null || request.getVideoList().isEmpty()) {
            throw new IllegalArgumentException("下载请求不能为空");
        }
        for (VideoDownLoadDto.VideoInfo video : request.getVideoList()) {
            if (video.getBvid() == null || video.getCid() == null) {
                throw new IllegalArgumentException("视频信息不完整: bvid=" + video.getBvid() + ", cid=" + video.getCid());
            }
            videoDownloadService.downloadVideo(video);
        }
    }


    @GetMapping("/download/list")
    public List<DownloadInfo> getDownloadList() {
        return videoDownloadService.getDownloadList();
    }

    @GetMapping("/download/folder-path")
    public Map<String, String> getDownloadFolderPath() {
        Map<String, String> result = new HashMap<>();
        try {
            String resolvedPath = getResolvedDownloadPath();
            File folder = new File(resolvedPath);
            result.put("configuredPath", downloadPath);
            result.put("resolvedPath", resolvedPath);
            result.put("exists", String.valueOf(folder.exists()));
            result.put("canWrite", String.valueOf(folder.canWrite()));
            result.put("absolutePath", folder.getAbsolutePath());
            return result;
        } catch (Exception e) {
            result.put("error", e.getMessage());
            return result;
        }
    }

    @PostMapping("/download/retry/{downloadId}")
    public void retryDownload(@PathVariable String downloadId) {
        videoDownloadService.retryDownload(downloadId);
    }

    @DeleteMapping("/download/{downloadId}")
    public void deleteDownload(@PathVariable String downloadId) {
        videoDownloadService.deleteDownload(downloadId);
    }

    @DeleteMapping("/download/completed")
    public void clearCompletedDownloads() {
        videoDownloadService.clearCompletedDownloads();
    }

    private String getResolvedDownloadPath() {
        return downloadPath.replace("${user.home}", System.getProperty("user.home"));
    }
}
